<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;
use App\Repositories\CustomerRepository;
use App\Http\Requests\CustomerRequest;
use App\Http\Requests\CustomerMoveRequest;
use App\Repositories\OrderRepository;
use App\Repositories\RenewRepository;
use App\Repositories\UserRepository;
use App\Repositories\DepartmentRepository;
use App\Services\PHPTree;

class CustomerController extends AdminController
{

    public function __construct(
        CustomerRepository $customer, 
        OrderRepository $order, 
        RenewRepository $renew, 
        UserRepository $user,
        DepartmentRepository $department
    )
    {
        $this->customer = $customer;
        $this->order = $order;
        $this->renew = $renew;
        $this->user = $user;
        $this->department = $department;
    }

    /**
     * Display a listing of the resource.
     *
     * @return Response
     */
    public function index(Request $request)
    {
        $where = collect($request->except('page'));

        $user = $request->user();

        $items = [];
        $tpl = 'list';

        if ($user->group->level == 3) {
            // 业务员
            $where->put('saler_id', $user->id);
            $tpl = 'list-3';
        } elseif ($user->group->level == 4) {
            // 业务经理
            $where->put('department_id', $user->department_id);
            $tpl = 'list-4';

            $items['salers'] = $this->user->salerSelect(['department_id'=>$user->department_id])->prepend('请选择业务员', 0);
        } elseif ($user->group->level == 8) {
            // 业务总监
            $where->put('region_id', $user->region_id);
            $tpl = 'list-8';

            $items['salers'] = $this->user->getSalersByDepartment();
            $items['departmentsTree'] = (new PHPTree($this->department->all()))->render();

        } else {
            // 其他人
            $departmentsTree = (new PHPTree($this->department->all()))->render();
            $salers = $this->user->getSalersByDepartment();

            $items = [
                'departmentsTree' => $departmentsTree,
                'salers'          => $salers,
            ];
        }

        $items['where'] = $where;
        $items['data']  = $this->customer->paginateList($where);
        $items['user'] = $user;

        return view('admin.customer.'.$tpl, $items);
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return Response
     */
    public function show($id, OrderRepository $order)
    {
        $customer = $this->customer->find($id);

        // 判断该用户是否该客户的拥有者
        $this->user->owner($customer->saler_id, auth()->user(), '您没有权限查看该客户的订单详细。');

        // 订单
        $orders = $this->order->findAllBy('cid',  $id);

        //续费
        $renews = collect();
        if (!$orders->isEmpty()) {
            $renews = $this->renew->getLists($orders->pluck('id'));
        }

        return view('admin.customer.show', compact('customer', 'orders', 'renews'));
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return Response
     */
    public function edit(Request $request, $id)
    {
        $data = $this->customer->find($id);
        $this->user->owner($data->saler_id, $request->user(), '您没有权限修改该客户信息。');

        return view('admin.customer.edit', compact('data'));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  Request  $request
     * @param  int  $id
     * @return Response
     */
    public function update(CustomerRequest $request, $id)
    {
        $data = $this->customer->find($id);
        $this->user->owner($data->saler_id, $request->user(), '您没有权限修改该客户信息。');

        $result = $data->update($request->all());

        $referer = $request->input('referer');
        $goto = $referer ? redirect($referer) : back();  

        if ($result) {
            return $goto->with('success', '客户信息更新成功'); 
        }

        return $goto->with('error', '客户信息更新失败');
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return Response
     */
    public function destroy($id)
    {
        $data = $this->customer->find($id);

       if ($data->order->count() > 0) {
            flash('error', '客户删除失败, 请转移该客户的订单后再删除');
            return response()->json(['code' => 500]);
       }

       if ($data->delete()) {
            flash('success', '客户删除成功');
            return response()->json(['code' => 200]);
       }

       flash('error', '客户删除失败');
       return response()->json(['code' => 500]);
    }

    // 转移客户
    public function move(CustomerMoveRequest $request)
    {   
        // 要转移的客户信息ID
        $ids = explode('-', $request->input('ids'));

        if (!empty($ids)) {
            $salerId = $request->input('saler_id');
            $user = $this->user->find($salerId);

            // 如果操作用户为业务总监，则需要判断是否有权限
            if ($request->user()->group->level == 8) {
                // 限制业务总监要转移到的用户必须是本区域的
                if ($user->region_id != $request->user()->region_id) {
                    return back()->with('error', '请不要选择区域外用户');
                }
                // 业务总监只能操作本区域的客户
                $checkMsg = $this->customer->checkIsRegion($ids, $request->user()->region_id);
                if ($checkMsg != '') {
                    return back()->with('error', $checkMsg);
                }
            }

            if ($user) {
                if (is_numeric($salerId) && $salerId > 0) {
                    // 转移客户
                    $this->customer->updateSaler($ids, $salerId);

                    // 转移订单
                    $this->order->updateSaler($ids, $salerId);

                    // 转移续费
                    $this->renew->updateSaler($ids, $salerId);

                    return back()->with('success', '客户信息转移成功');
                }
            } else {
                return back()->with('error', '你选择业务员不存在');
            }

            return back()->with('error', '客户信息更新失败');
        }
    }

    // 拉取客户信息
    public function loadPull(Request $request)
    {
        $name = trim($request->input('name'));
        return $this->customer->getCustomerContractByName($name);
    }
}
